package org.hiucung.desktoptranslationtools.dialog

import java.io.File
import javax.swing.JFileChooser
import javax.swing.SwingUtilities
import javax.swing.filechooser.FileNameExtensionFilter

fun openDirectorDialog(title: String = "打开项目目录", path: String = ""): String {
    // 设置系统样式
//    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
    val folderChooser = JFileChooser()
    folderChooser.dialogTitle = title
    path.takeIf { it.isNotEmpty() }?.run {
        folderChooser.currentDirectory = File(path)
    }
    folderChooser.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY // 限制为仅选择目录
    val result = folderChooser.showOpenDialog(null)
    return if (result == JFileChooser.APPROVE_OPTION) {
        folderChooser.selectedFile.absolutePath // 返回所选目录的绝对路径
    } else {
        ""
    }
}

fun openFileDialog(
    title: String = "选择文件",
    description: String = "",
    path: String = "",
    vararg suffixNames: String
): String {
    // 设置系统样式
//    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
    val folderChooser = JFileChooser()
    folderChooser.dialogTitle = title
    path.takeIf { it.isNotEmpty() }?.run {
        folderChooser.selectedFile = File(path)
    }
    folderChooser.fileFilter = FileNameExtensionFilter(description, *suffixNames)
    folderChooser.fileSelectionMode = JFileChooser.FILES_ONLY // 限制为仅选择目录

    val result = folderChooser.showOpenDialog(null)
    return if (result == JFileChooser.APPROVE_OPTION) {
        folderChooser.selectedFile.absolutePath // 返回所选目录的绝对路径
    } else {
        ""
    }
}


fun openSaveFileDialog(
    title: String = "选择文件",
    description: String = "",
    path: String = "",
    selectFilePath: (filePath: String) -> Unit = {},
    vararg suffixNames: String
) {
    SwingUtilities.invokeLater {
        // 设置系统样式
//        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
        val folderChooser = JFileChooser()
        folderChooser.dialogTitle = title
        path.takeIf { it.isNotEmpty() }?.run {
            folderChooser.currentDirectory = File(path)
        }
        folderChooser.fileFilter = FileNameExtensionFilter(description, *suffixNames)
        folderChooser.fileSelectionMode = JFileChooser.FILES_ONLY // 限制为仅选择目录
        val result = folderChooser.showSaveDialog(null)
        selectFilePath.invoke(
            if (result == JFileChooser.APPROVE_OPTION) {
                folderChooser.selectedFile.absolutePath // 返回所选目录的绝对路径
            } else {
                ""
            }
        )
    }
}

// 文件选择器函数
//fun openFileDialog(title:String="打开项目目录"): String? {
//    // 使用 AWT 的 FileDialog
//    val fileDialog = FileDialog(ComposeWindow(), title, FileDialog.LOAD).apply {
//        this.file="*.xlsx;*.xls"
//    }
//    fileDialog.isVisible = true
//    return fileDialog.file?.let { "${fileDialog.directory}$it" }
//}